package com.cqhz.quwan.ui.buy;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.TextView;

import com.cqhz.quwan.ActivityInject;
import com.cqhz.quwan.R;
import com.cqhz.quwan.model.Coupon;
import com.cqhz.quwan.mvp.buy.CouponContract;
import com.cqhz.quwan.mvp.buy.CouponPresenter;
import com.cqhz.quwan.ui.base.BaseDialogFragment;
import com.cqhz.quwan.ui.base.BaseRecyclerViewAdapter;
import com.cqhz.quwan.ui.buy.event.EventObj;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import me.militch.quickcore.core.HasDaggerInject;
import me.militch.quickcore.util.ApiException;

/**
 * <p>底部弹出优惠券</p>
 *
 * @author whamu2
 * @date 2018/6/9
 */
public class CouponDialog extends BaseDialogFragment implements CouponContract.View, HasDaggerInject<ActivityInject> {
    private static final String TAG = CouponDialog.class.getSimpleName();
    private static final String KEY_ID = "order_id";
    private static final String KEY_COUPON = "coupon_id";

    @Inject
    CouponPresenter mPresenter;

    CheckedTextView mUnusedCheckedTextView;
    RecyclerView mRecyclerView;
    TextView mEmptyTextView;
    private Adapter adapter;

    private String selectedCouponId;

    public static CouponDialog newInstance(String orderId) {
        Bundle args = new Bundle();
        args.putString(KEY_ID, orderId);
        CouponDialog fragment = new CouponDialog();
        fragment.setArguments(args);
        return fragment;
    }

    public static CouponDialog newInstance(String orderId, String couponId) {
        Bundle args = new Bundle();
        args.putString(KEY_ID, orderId);
        args.putString(KEY_COUPON, couponId);
        CouponDialog fragment = new CouponDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int gentleDialogStyle() {
        return 0;
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.BOTTOM;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setCancelable(false);
    }


    @Override
    protected View gentleLayout(LayoutInflater inflater,
                                @Nullable ViewGroup container,
                                @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dialog_bottom_coupon, container, false);
    }

    @Override
    protected void gentleViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mPresenter.attachView(this);
        mUnusedCheckedTextView = view.findViewById(R.id.ctv_unused_coupon);
        mRecyclerView = view.findViewById(R.id.rv);
        mEmptyTextView = view.findViewById(R.id.tv_empty);
        view.findViewById(R.id.tv_commit).setOnClickListener(this::onClick);
        mUnusedCheckedTextView.setOnClickListener(this::onClick);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new Adapter(getContext());
        mRecyclerView.setAdapter(adapter);

        if (getArguments() != null) {
            String orderId = getArguments().getString(KEY_ID);
            selectedCouponId = getArguments().getString(KEY_COUPON);
            if (!TextUtils.isEmpty(orderId)) {
                mPresenter.getCouponList(orderId);
            }
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_commit:
                List<Coupon> items = new ArrayList<>();
                if (adapter != null) {
                    for (Coupon coupon : adapter.getData()) {
                        if (coupon.isChecked()) {
                            items.add(coupon);
                        }
                    }
                }
                EventBus.getDefault().post(new EventObj(0x111110, items));
                dismiss();
                break;
            case R.id.ctv_unused_coupon:
                if (!mUnusedCheckedTextView.isChecked() && adapter != null) {
                    for (Coupon coupon : adapter.getData()) {
                        coupon.setChecked(false);
                    }
                    adapter.notifyDataSetChanged();
                }
                EventBus.getDefault().post(new EventObj(0xFFF, "notUse"));
                mUnusedCheckedTextView.toggle();
                break;
        }
    }

    @Override
    public void showList(List<Coupon> data) {
        mEmptyTextView.setVisibility(data != null && data.size() > 0 ? View.GONE : View.VISIBLE);

        List<Coupon> coupons = new ArrayList<>();
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                Coupon coupon = data.get(i);
                if (!TextUtils.isEmpty(selectedCouponId) && TextUtils.equals(selectedCouponId, coupon.getCouponId())) {
                    coupon.setChecked(true);
                }
                coupons.add(coupon);
            }
        }
        adapter.setData(coupons);
    }

    @Override
    public void showRequestError(ApiException e) {

    }

    @Override
    public void inject(ActivityInject activityInject) {
        activityInject.inject(this);
    }


    public class Adapter extends BaseRecyclerViewAdapter<Coupon, Adapter.ViewHolder> {

        Adapter(Context c) {
            super(c);
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.item_coupon_layout, parent, false));
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Coupon item = getItem(position);
            holder.mAmountTextView.setText(item.getMoney().toString());
            holder.mTitleTextView.setText(item.getLotteryName());
            String aMoney = String.format("单笔订单%s元可用", item.getConditionMoney().toString());
            String aEndTime = String.format("有效期限至%s", item.getEndTime());
            holder.mDesTextView.setText(aMoney);
            holder.mTimeTextView.setText(aEndTime);
            holder.mCheckBox.setChecked(item.isChecked());

            holder.itemView.setOnClickListener(v -> {
                for (Coupon coupon : getData()) {
                    coupon.setChecked(false);
                }
                getItem(position).setChecked(true);
                if (mUnusedCheckedTextView != null) {
                    mUnusedCheckedTextView.setChecked(false);
                }
                notifyDataSetChanged();
            });
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView mAmountTextView; // 优惠券金额
            TextView mTitleTextView;  // 标题
            TextView mDesTextView;    // 可用条件
            TextView mTimeTextView;   // 有效时间
            CheckBox mCheckBox;

            public ViewHolder(View itemView) {
                super(itemView);
                mAmountTextView = itemView.findViewById(R.id.tv_amount);
                mTitleTextView = itemView.findViewById(R.id.tv_title);
                mDesTextView = itemView.findViewById(R.id.tv_des);
                mTimeTextView = itemView.findViewById(R.id.tv_time);
                mCheckBox = itemView.findViewById(R.id.cb);
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }
}
